package com.leesche.zcsp.node.web.controller.web.v2.individual;

import com.leesche.zcsp.node.app.v1.timer.PhoneCodeCacheTimer;
import com.leesche.zcsp.node.app.v1.timer.VaildPhone;
import com.leesche.zcsp.node.app.v1.vo.UserInfo;
import com.leesche.zcsp.node.communication.service.SmsService;
import com.leesche.zcsp.node.utils.calculator.Calculation;
import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.filemanager.FileManager;
import com.leesche.zcsp.node.utils.web.gernerator.TimeGreaterUilt;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.sms.SmsController;
import com.leesche.zcsp.node.web.dao.SysUserPlaceDao;
import com.leesche.zcsp.node.web.model.*;
import com.leesche.zcsp.node.web.service.*;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.service.impl.data.writ.AddBankCardCommand;
import com.leesche.zcsp.node.web.service.impl.data.writ.AddUserInfoCommand;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Principal;
import com.leesche.zcsp.node.web.vo.Privilege;
import com.leesche.zcsp.node.web.vo.UserGroup;
import com.leesche.zcsp.node.web.vo.v2.*;
import com.leesche.zcsp.node.web.vo.v2.enums.WhereaboutsEnum;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Jerry Chan
 * @version V1.0
 *          ************ * Jerry Chan: * 2016/12/7 14:52: * 创建该类并实现业务逻辑: *********
 * @Title: WebIndividualController.java
 * @Description: TODO( “我的”Controller类)
 * @date 2016/12/7 14:52
 */
@Controller
@RequestMapping("/v2/individual")
public class WebIndividualController {

    private static final Logger logger = Logger.getLogger(WebIndividualController.class);

    @Autowired
    private PrivilegeService privilegeService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    protected SysRoleService sysRoleService;
    @Autowired
    private SysUserBalanceService sysUserBalanceService;
    @Autowired
    private SysNoticeService sysNoticeService;
    @Autowired
    private SysUserCashDetailService sysUserCashDetailService;
    @Autowired
    private SysUserBusinessInfoService sysUserBusinessInfoService;
    @Autowired
    private SysUserBankCardService sysUserBankCardService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private SysAuditPersonService sysAuditPersonService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysModuleService sysModuleService;
    @Autowired
    private SysRoleModuleService sysRoleModuleService;
    @Autowired
    private SysUserPlaceService sysUserPlaceService;
    @Autowired
    private PubPlaceService pubPlaceService;

    private static final String BUSINESSINFO_VIEW = "web/v2/individual/my_businessinfo";
    private static final String CHILDUSERINFO_VIEW = "web/v2/individual/my_childuserinfo";
    private static final String PLACEDEVICEMANAGE_VIEW = "web/v2/individual/my_plaecedevicemange";
    private static final String CHANGEMOBILE_VIEW = "web/v2/individual/my_changemobile";
    private static final String CHAENGLOGINPASSWORD_VIEW = "web/v2/individual/my_changloginpassword";
    private static final String CHAENGTRANSFERPASSWORD_VIEW = "web/v2/individual/my_changtransferpassword";
    private static final String BINDBANKCARD_VIEW = "web/v2/individual/my_bindBankcard";
    private static final String BALANCE_VIEW = "web/v2/individual/my_balance";
    private static final String TRANSFERBALANCE_VIEW = "web/v2/individual/my_transferbalance";
    private static final String UPLOADLOGO_VIEW = "web/v2/individual/my_uploadlogo";
    private static final String EDITBOTTOMCONTENT_VIEW = "web/v2/individual/my_editbottomcontenttext";
    private static final String GETAPPQRCODE_VIEW = "web/v2/individual/my_getappqrcode";
    private static final String ADDUSERGROUP_VIEW = "web/v2/individual/my_addusergroup";


    @RequestMapping(value = "/showchangemobileView", method = RequestMethod.GET)
    public String showChangeMobileView(Model model) {
        return CHANGEMOBILE_VIEW;
    }

    @RequestMapping(value = "/showchangloginpassowrdView", method = RequestMethod.GET)
    public String showChangeLoginPasswordView(Model model) {
        return CHAENGLOGINPASSWORD_VIEW;
    }

    @RequestMapping(value = "/showchangtransferpassowrdView", method = RequestMethod.GET)
    public String showChangeTransferPasswordView(Model model) {
        return CHAENGTRANSFERPASSWORD_VIEW;
    }

    /**
     * @Title: showView
     * @Description: TODO(显示添加角色界面)
     * @author Jerry Chan
     * @date 2016/12/12 19:40
     */
    @RequestMapping(value = "/showaddusergroupView", method = RequestMethod.GET)
    public String showAddUserGroupView(Model model) {

        Principal principal = privilegeService.getCurrentPrincipal();
        QuerySysRoleModuleCondition condition = new QuerySysRoleModuleCondition();
        condition.setAdminid(principal.getUserid());
        condition.setNtype(principal.getNtype());
        condition.setIsshare(1);
        condition.setIsdefault(1);
        condition.setState(1);
        List<Menu> menus = sysModuleService.findAllSysModuleTrees(condition);
        model.addAttribute("modules", menus);
        return ADDUSERGROUP_VIEW;
    }

    @ResponseBody
    @RequestMapping(value = "/showaddusergroup", method = RequestMethod.GET)
    public List<Menu> showAddUserGroup(Model model) {

        Principal principal = privilegeService.getCurrentPrincipal();

        QuerySysRoleModuleCondition condition = new QuerySysRoleModuleCondition();
        condition.setAdminid(principal.getUserid());
        condition.setNtype(principal.getNtype());
        condition.setIsshare(1);
        condition.setIsdefault(1);
        condition.setState(1);
        return sysModuleService.findAllSysModuleTrees(condition);

    }

    /**
     * @Title: showView
     * @Description: TODO(获取娱乐城老板的身份信息)
     * @author Jerry Chan
     * @date 2016/12/12 19:40
     */
    @RequestMapping(value = "/showView", method = RequestMethod.GET)
    public String showView(Model model) {
        SysUser user = sysUserService.selectByPrimaryKey(privilegeService.getCurrentPrincipal().getUserid());
        UserInfo userinfo = new UserInfo();
        if (user != null) {
            userinfo.setUsername(user.getUsername());
            userinfo.setBusinssno(user.getBusinessno() != null ? user.getBusinessno() : user.getUsername());
            userinfo.setMobile(user.getMobile());
            userinfo.setShortCode(user.getShortcode());
            userinfo.setRegisterTime(user.getCreatetime());
        }
        model.addAttribute("userinfo", userinfo);
        return BUSINESSINFO_VIEW;
    }

    @RequestMapping(value = "/showplacedevicemanageView", method = RequestMethod.GET)
    public String showPlaceDeviceManageView(Model model) {

        QuerySysUserCondition userCondition = new QuerySysUserCondition();
        userCondition.setParentid(privilegeService.getCurrentPrincipal().getUserid());
        List<SysUserDto> sysUserDtos = sysUserService.findListsByCondition(userCondition);

        QuerySysUserPlaceCondition condition = new QuerySysUserPlaceCondition();
        condition.setUserPerentID(privilegeService.getCurrentPrincipal().getUserid());
        List<SysUserPlaceDto> userPlaceDtos = sysUserPlaceService.findListsByCondition(condition);

        List<com.leesche.zcsp.node.web.vo.v2.UserInfo> users = new ArrayList<com.leesche.zcsp.node.web.vo.v2.UserInfo>();

        for (SysUserDto sysuser : sysUserDtos) {
            com.leesche.zcsp.node.web.vo.v2.UserInfo user = new com.leesche.zcsp.node.web.vo.v2.UserInfo();
            user.setUserid(sysuser.getUserid());
            user.setUsername(sysuser.getUsername());
            user.setPlaces(new ArrayList<PlaceVo>());

            for (int i = 0; i < userPlaceDtos.size(); i++) {
                if (userPlaceDtos.get(i).getUserid().equals(user.getUserid())) {
                    PlaceVo place = new PlaceVo();
                    place.setPlaceid(userPlaceDtos.get(i).getPlaceid());
                    place.setPlacename(userPlaceDtos.get(i).getAddress());
                    user.getPlaces().add(place);
                }
            }
            users.add(user);
        }
        model.addAttribute("childuser", users);
        return PLACEDEVICEMANAGE_VIEW;
    }

    @RequestMapping(value = "/showchildView", method = RequestMethod.GET)
    public String showChildUserInfoView(Model model) {

        Long userid = privilegeService.getCurrentPrincipal().getUserid();
        QuerySysRoleCondition condition = new QuerySysRoleCondition();
        condition.setNtype(privilegeService.getCurrentPrincipal().getNtype());
        condition.setAdminid(userid);
        List<SysRole> sysRoles = sysRoleService.findChildRolesByCondition(condition);

        List<RoleVo> roles = new ArrayList<RoleVo>();
        for (SysRole sysrole : sysRoles) {
            RoleVo role = new RoleVo();
            role.setName(sysrole.getNamecn());
            role.setId(sysrole.getRoleid());
            roles.add(role);
        }

        model.addAttribute("usergroups", roles);

        return CHILDUSERINFO_VIEW;
    }

    /**
     * @return
     * @Title: showBindBankCardView(Model model)
     * @Description: TODO(显示用户银行卡)
     * @author Jerry Chan
     * @date 2016/12/29 16:31
     */
    @RequestMapping(value = "/showbindbankcardView", method = RequestMethod.GET)
    public String showBindBankCardView(Model model) {
        QuerySysUserBankCardCondition condition = new QuerySysUserBankCardCondition();
        condition.setUserid(privilegeService.getCurrentPrincipal().getUserid());
        SysUserBankCardDto dto = sysUserBankCardService.findByCondition(condition);
        BankCardVo vo = null;
        if (dto != null) {
            vo = new BankCardVo();
            vo.setCardid(dto.getCardid());
            String name = dto.getCardholder();
            vo.setCardholder("*" + name.substring(1, name.length()));
            String cardnumber = dto.getBankcardnumber();
            vo.setBankcardnumber("**** **** **** **** " + cardnumber.substring(cardnumber.length() - 4, cardnumber.length()));
        }

        model.addAttribute("card", vo);
        return BINDBANKCARD_VIEW;
    }

    @RequestMapping(value = "/showbalanceView", method = RequestMethod.GET)
    public String showBalanceView(Model model) {
        QuerySysUserBalanceCondition querySysUserBalanceCondition = new QuerySysUserBalanceCondition();
        querySysUserBalanceCondition.setUserId(privilegeService.getCurrentPrincipal().getUserid());
        SysUserBalanceDto userBalanceDto = sysUserBalanceService
                .findByCondition(querySysUserBalanceCondition);
        String money = "0.00";
        //Long currentMoney = userBalanceDto.getCurrentmoney();
        if (userBalanceDto != null && userBalanceDto.getCurrentmoney() > 0) {
            money = Calculation.addition(userBalanceDto.getCurrentmoney());
        }
        model.addAttribute("money", money);
        return BALANCE_VIEW;
    }

    @RequestMapping(value = "/showtransferbalanceView", method = RequestMethod.GET)
    public String showTransferBalanceView(Model model) {

        QuerySysUserBusinessInfoCondition condition = new QuerySysUserBusinessInfoCondition();
        condition.setUserid(privilegeService.getCurrentPrincipal().getUserid());
        condition.setQueryAll(true);
        SysUserBusinessInfoDto dto = sysUserBusinessInfoService.findByCondition(condition);
        Float rate = dto.getRate();
        model.addAttribute("rate", rate);

        return TRANSFERBALANCE_VIEW;
    }

    @RequestMapping(value = "/showuploadlogoView", method = RequestMethod.GET)
    public String showUploadLogoView(Model model) {
        String logo = "";
        boolean flag = true;
        SysNoticeDto sysNotice = sysNoticeService.findSysNotice(Integer.parseInt(privilegeService.getCurrentPrincipal().getUserid().toString()));
        if (sysNotice != null && !"".equals(sysNotice.getLogourl())) {
            logo = sysNotice.getLogourl();
            flag = true;
        } else {
            logo = Constants.SYSTEM_WEB_DEFAULT_UPLOADIMAGE;
            flag = false;
        }

        model.addAttribute("islogo", flag);
        model.addAttribute("logo", logo);


        return UPLOADLOGO_VIEW;
    }

    /**
     * @Title: showEditBottomContentView(Model model)
     * @Description: TODO(显示编辑底部文字界面)
     * @author Jerry Chan
     * @date 2016/12/21 11:28
     */
    @RequestMapping(value = "/showeditbottomcontentView", method = RequestMethod.GET)
    public String showEditBottomContentView(Model model) {
        String content = "";
        SysNoticeDto sysNotice = sysNoticeService.findSysNotice(Integer.parseInt(privilegeService.getCurrentPrincipal().getUserid().toString()));
        if (sysNotice != null && !"".equals(sysNotice.getButtomcontent())) {
            content = sysNotice.getButtomcontent();
        } else {
            content = Constants.NOTIC_DEFAULT_BUTTOMCONTENT;
        }
        model.addAttribute("bottomcontent", content);
        return EDITBOTTOMCONTENT_VIEW;
    }

    @RequestMapping(value = "/showegetappqrcodeView", method = RequestMethod.GET)
    public String showGetAppQRCodeView(Model model) {
        return GETAPPQRCODE_VIEW;
    }

    /**
     * @Title: changeMobileNumber(String mobileCode, String mobileNumber, HttpSession session)
     * @Description: TODO(更换当前用户的手机号码)
     * @author Jerry Chan
     * @date 2016/12/15 21:25
     */
    @ResponseBody
    @RequestMapping(value = "changmobile", method = RequestMethod.POST)
    public Map<String, Object> changeMobileNumber(String mobileCode, String mobileNumber) {
        try {
            if (mobileCode == null || "".equals(mobileCode)) {
                return WebResult.failure("短信验证码不能为空").toMap();
            }
            if (mobileNumber == null || "".equals(mobileNumber)) {
                return WebResult.failure("手机号码不能为空").toMap();
            }
            SysUser user = new SysUser();
            user.setMobile(mobileNumber);
            if (sysUserService.findUserByUsername(user) != null) {
                return WebResult.failure("手机号已被使用,请更换其他手机号").toMap();
            }

            user = sysUserService.selectByPrimaryKey(privilegeService.getCurrentPrincipal().getUserid());
            VaildPhone validPhone = PhoneCodeCacheTimer.get(mobileCode);
            if (validPhone == null) {
                return WebResult.failure("验证码错误,请重新输入").toMap();
            } else if (validPhone.getValidTime() < new Date().getTime()) {
                PhoneCodeCacheTimer.remove(mobileCode);
                return WebResult.failure("短信验证码已过期，请重新获取").toMap();
            }else{
                if (user == null || "".equals(user.getMobile())) {
                    return WebResult.failure("用户没有手机号码").toMap();
                }else if (!validPhone.getPhone().equals(user.getMobile())) {
                    return WebResult.failure("与获取短信的手机号码一致").toMap();
                } else {
                    PhoneCodeCacheTimer.remove(mobileCode);
                }
            }

            SysUser newUser = new SysUser();
            newUser.setUserid(user.getUserid());
            newUser.setAdminid(user.getUserid());
            newUser.setUpdatetime(new Date());
            user.setMobile(mobileNumber);
            if(sysUserService.updateByPrimaryKeySelective(user) > 0){
                return WebResult.success().toMap();
            }else{
                return WebResult.failure("更改手机号码失败，请与管理员联系").toMap();
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }

    }

    /**
     * @Title: changLoginPassword(String mobileCode, String oldpassword, String newpassword, HttpSession session)
     * @Description: TODO(修改当前用户的登录密码)
     * @author Jerry Chan
     * @date 2016/12/15 21:25
     */
    @ResponseBody
    @RequestMapping(value = "changloginpassword", method = RequestMethod.POST)
    public Map<String, Object> changLoginPassword(String mobileCode, String oldpassword, String newpassword) {
        try {
            return this.changePassword(1, mobileCode, oldpassword, newpassword);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @return
     * @Title: changTrnsferPassword(String mobileCode, String oldpassword, String newpassword, HttpSession session)
     * @Description: TODO(修改用户提现密码)
     * @author Jerry Chan
     * @date 2016/12/16 11:29
     */
    @ResponseBody
    @RequestMapping(value = "changtransferpassword", method = RequestMethod.POST)
    public Map<String, Object> changTrnsferPassword(String mobileCode, String oldpassword, String newpassword) {
        try {
            return this.changePassword(2, mobileCode, oldpassword, newpassword);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @return
     * @Title: uploadLogo(MultipartFile logo)
     * @Description: TODO(上传logo)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "uplaodLogo", method = RequestMethod.POST)
    public Map<String, Object> uploadUserLogo(@RequestParam(value = "logo", required = false) MultipartFile file) {

        String logopath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME, Constants.SYSTEM_TMAGE_USERLOGO_DIRECTORY);
        String logoSaveResult = FileManager.saveImage(file, logopath);
        if (logoSaveResult.contains(FileManager.ERRORSTR)) {
            return WebResult.failure(logoSaveResult.replace(FileManager.ERRORSTR, "")).toMap();
        } else {
            Long userid = privilegeService.getCurrentPrincipal().getUserid();
            SysNotice notice = new SysNotice();
            notice.setLogourl(SessionManager.getWebServerURL() + Constants.SYSTEM_TMAGE_USERLOGO_DIRECTORY + "/" + logoSaveResult);
            notice.setUpdatetime(new Date());
            notice.setAdminid(userid);
            notice.setUserid(userid);
            if (sysNoticeService.addOrUpdateNotice(notice) > 0) {
                return WebResult.success().toMap();
            } else {
                return WebResult.failure("上传图片失败").toMap();
            }

        }
    }

    /**
     * @return
     * @Title: editBottomContent(String content, HttpSession session)
     * @Description: TODO(编辑底部文字)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "editContent", method = RequestMethod.POST)
    public Map<String, Object> editBottomContent(String content) {
        try {

            if (content == null || "".equals(content)) {
                return WebResult.failure("文字不能为空").toMap();
            }

            Long userid = privilegeService.getCurrentPrincipal().getUserid();

            SysNotice notice = new SysNotice();
            notice.setButtomcontent(content);
            notice.setUpdatetime(new Date());
            notice.setAdminid(userid);
            notice.setUserid(userid);
            if (sysNoticeService.findSysNotice(Integer.parseInt(userid.toString())) != null) {
                SysNoticeCriteria criteria = new SysNoticeCriteria();
                criteria.or().andUseridEqualTo(notice.getUserid());
                //修改底部文字
                sysNoticeService.updateByCriteriaSelective(notice, criteria);
            } else {
                // 增加底部文字
                sysNoticeService.insertSelective(notice);
            }

            return WebResult.success().toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param page 页数
     * @Title: editBottomContent(String content, HttpSession session)
     * @Description: TODO(显示提现流水详情)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "showbalancedatail", method = RequestMethod.GET)
    public Map<String, Object> showUserBalanceDetail(Integer page) {
        try {
            QuerySysUserCashDetailCondition condition = new QuerySysUserCashDetailCondition();
            condition.setUserId(privilegeService.getCurrentPrincipal().getUserid());
            condition.setPage(page == null ? 1 : page);
            condition.setRows(Constants.NOTIC_DEFAULT_PAGEING_ROWS_MAXNUMBER);
            List<SysUserCashDetailDto> userCashDetailDtos = sysUserCashDetailService.findListsByCondition(condition);
            if (userCashDetailDtos == null || userCashDetailDtos.size() <= 0) {
                return WebResult.failure(condition.getPage() > 1 ? "已经没有更多数据了" : "尚未提现").toMap();
            }
            List<CashDetailVo> cashDetailVOs = new ArrayList<CashDetailVo>();
            for (SysUserCashDetailDto dto : userCashDetailDtos) {
                CashDetailVo vo = new CashDetailVo();
                vo.setCashDetailID(dto.getCashdetailid());
                vo.setCashWhereabouts(WhereaboutsEnum.getText(dto.getLosttype() == null || "".equals(dto.getLosttype()) ? 0 : Integer.parseInt(dto.getLosttype().toString())));
                vo.setCashTime(dto.getReceivetime());
                vo.setCachState(dto.getLoststatus() == 0 ? "已到账" : "未到账");
                vo.setCachAmount(dto.getLostmoney() == null || "".equals(dto.getLostmoney()) ? "0.00" : Calculation.addition(dto.getLostmoney()));
                cashDetailVOs.add(vo);
            }
            return WebResult.success().put("details", cashDetailVOs).toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: showUserBalanceDetailTotalRecord()
     * @Description: TODO(显示提现流水账分页的总页数)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "getdatailtotalrecord", method = RequestMethod.GET)
    public Map<String, Object> showUserBalanceDetailTotalRecord() {
        try {
            SysUserCashDetailCriteria criteria = new SysUserCashDetailCriteria();
            criteria.or().andUseridEqualTo(privilegeService.getCurrentPrincipal().getUserid());
            Long countRows = sysUserCashDetailService.countByCriteria(criteria);
            Integer pageMaxRowsNumber = Constants.NOTIC_DEFAULT_PAGEING_ROWS_MAXNUMBER;
            return WebResult.success().put("TotalRecord", (countRows + pageMaxRowsNumber - 1) / pageMaxRowsNumber).toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: showUserBalanceDetailTotalRecord()
     * @Description: TODO(显示提现流水账分页的总页数)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "verifyTransferPassword", method = RequestMethod.GET)
    public Map<String, Object> verifyTransFerPassword(final String password) {
        try {

            if (password == null || "".equals(password)) {
                return WebResult.failure("提现密码不能为空").toMap();
            }

            SysUser user = sysUserService.selectByPrimaryKey(privilegeService.getCurrentPrincipal().getUserid());
            String userTransferPassword = user.getTransferpassword();
            if (userTransferPassword == null || "".equals(userTransferPassword)) {
                return WebResult.failure("尚未设置提现密码").toMap();
            } else if (QEncodeUtil.md5Encrypt(password).equals(userTransferPassword)) {
                return WebResult.success().toMap();
            } else {
                return WebResult.failure("提现密码错误，请重新输入").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: showUserBalanceDetailTotalRecord()
     * @Description: TODO(显示提现流水账分页的总页数)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "editbankcard", method = RequestMethod.POST)
    public Map<String, Object> bindBankCard(AddBankCardCommand bankCard) {
        try {

            Long userid = privilegeService.getCurrentPrincipal().getUserid();
            QuerySysUserBankCardCondition condition = new QuerySysUserBankCardCondition();
            condition.setUserid(userid);
            condition.setCardid(bankCard.getCardid());
            SysUserBankCardDto carddto = sysUserBankCardService.findByCondition(condition);
            if (carddto == null) {
                return WebResult.failure("尚未绑定银行卡").toMap();
            }

/*            //保存身份证正面照
            String positiveSaveResult = FileManager.saveImage(bankCard.getIdcrardimgpositive(), Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY);
            if (positiveSaveResult.contains(FileManager.ERRORSTR))
                return WebResult.failure(positiveSaveResult.replace(FileManager.ERRORSTR, "")).toMap();

            //保存身份证反面照
            String behindSaveResult = FileManager.saveImage(bankCard.getIdcrardimgbehind(), Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY);
            if (behindSaveResult.contains(FileManager.ERRORSTR))
                return WebResult.failure(behindSaveResult.replace(FileManager.ERRORSTR, "")).toMap();

            String licenseSaveResult = FileManager.saveImage(bankCard.getBusinesslicense(), Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY);
            if (licenseSaveResult.contains(FileManager.ERRORSTR))
                return WebResult.failure(behindSaveResult.replace(FileManager.ERRORSTR, "")).toMap();*/

            SysUserBankCard card = new SysUserBankCard();
            card.setUserid(userid);
            card.setAdminid(userid);
            card.setCardid(bankCard.getCardid());
            card.setCardholder(bankCard.getCardholder());
            card.setBankcardnumber(bankCard.getBankcardnumber().replaceAll("\\s*", ""));
            card.setBankname(bankCard.getBankname());
            card.setMobile(bankCard.getMobile());
            card.setIdcard(bankCard.getIdcard());
            card.setPayunionbank(bankCard.getPayunionbank());
            card.setBankcountry(bankCard.getBankcountry());
            card.setBankprovince(bankCard.getBankprovince());
            card.setBankcity(bankCard.getBankcity());
            card.setBankofdeposit(bankCard.getBankofdeposit());
            card.setAccounttype(bankCard.getAccounttype());
            card.setBussinseclearingbank(bankCard.getBussinseclearingbank());
            card.setClearingcycle(bankCard.getClearingcycle());
            card.setCapitalclearingtype(bankCard.getCapitalclearingtype());
            card.setCardconfirmed(0);//修改后,需重新审核
            card.setUpdatetime(new Date());
            /*card.setIdcrardimgpositive(Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY + "/" + positiveSaveResult);
            card.setIdcrardimgbehind(Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY + "/" + behindSaveResult);
            card.setBusinesslicense(Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY + "/" + licenseSaveResult);*/
            int result = sysUserBankCardService.updateByPrimaryKeySelective(card);
            if (result > 0) {
                //进件受理通知(给客户)
                smsService.giveInfoAcceptSMS(carddto.getMobile(), carddto.getCardholder());
                //进件受理通知(给审核员)
                List<SysAuditPersonDto> personDtos = sysAuditPersonService.findListsByCondition(new QuerySysAuditPersonCondition());
                if (personDtos != null && personDtos.size() > 0) {
                    List<String> mobiles = new ArrayList<String>();
                    for (SysAuditPersonDto dto : personDtos) {
                        mobiles.add(dto.getPersonmobile());
                    }
                    smsService.giveInfoNotifySMS(mobiles, carddto.getCardholder());
                }

                return WebResult.success().toMap();
            } else
                return WebResult.failure("修改银行卡失败").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }


    /**
     * @Title: showUserBalanceDetailTotalRecord()
     * @Description: TODO(显示提现流水账分页的总页数)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "getchilduser", method = RequestMethod.POST)
    public Map<String, Object> getchilduserinfo(final Long usergroupid) {
        try {
            QuerySysUserRoleCondition condition = new QuerySysUserRoleCondition();
            condition.setUserid(privilegeService.getCurrentPrincipal().getUserid());
            condition.setRoleid(usergroupid);
            List<SysUserRoleDto> dtos = sysUserRoleService.findListsByCondition(condition);
            List<UserInfo> userInfos = new ArrayList<UserInfo>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (SysUserRoleDto dto : dtos) {
                UserInfo user = new UserInfo();
                user.setUserid(dto.getUserid());
                user.setUsername(dto.getUsername());
                user.setRegTime(format.format(dto.getCreatetime()));
                userInfos.add(user);
            }
            return WebResult.success().put("userinfos", userInfos).toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: recoverPassowrd(final Long userid)
     * @Description: TODO(重置子账户密码)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "recoverpassword", method = RequestMethod.POST)
    public Map<String, Object> recoverPassowrd(final Long userid) {
        try {
            SysUser newUser = new SysUser();
            newUser.setUserid(userid);
            newUser.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
            newUser.setUpdatetime(new Date());
            newUser.setPassword(QEncodeUtil.md5Encrypt(Constants.NOTIC_DEFAULT_USER_PASSWORD));
            if (sysUserService.updateByPrimaryKeySelective(newUser) > 0)
                return WebResult.success().toMap();
            else
                return WebResult.failure("恢复密码失败，请与管理员联系").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: changeChildUserPassowrd(final Long userid, final String password)
     * @Description: TODO(修改子账户密码)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "changechilduserpass", method = RequestMethod.POST)
    public Map<String, Object> changeChildUserPassowrd(final Long userid, final String password) {
        try {
            SysUser newUser = new SysUser();
            newUser.setUserid(userid);
            newUser.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
            newUser.setUpdatetime(new Date());
            newUser.setPassword(QEncodeUtil.md5Encrypt(password));
            if (sysUserService.updateByPrimaryKeySelective(newUser) > 0)
                return WebResult.success().toMap();
            else
                return WebResult.failure("修改密码失败，请与管理员联系").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: revomeChildUser(final Long userid)
     * @Description: TODO(删除子账户)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "removechilduser", method = RequestMethod.POST)
    public Map<String, Object> revomeChildUser(final Long userid) {
        try {
            //移除子账户的角色
            SysUserRoleCriteria criteria = new SysUserRoleCriteria();
            criteria.or().andUseridEqualTo(userid);
            sysUserRoleService.deleteByCriteria(criteria);
            //删除子账户信息
            if (sysUserService.deleteByPrimaryKey(userid) > 0)
                return WebResult.success().toMap();
            else
                return WebResult.failure("删除子账户失败，请与管理员联系").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }


    /**
     * @Title: addChildUser(AddUserInfoCommand childUser)
     * @Description: TODO(娱乐城老板新增子账户)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "addchilduser", method = RequestMethod.POST)
    public Map<String, Object> addChildUser(AddUserInfoCommand childUser) {
        try {

            SysUser newUser = new SysUser();
            newUser.setUsername(childUser.getUsername());
            if (sysUserService.findUserByUsername(newUser) != null) {
                return WebResult.failure("'" + childUser.getUsername() + "'用户名已经存在，请使用其他用户名").toMap();
            }

            Principal parentUser = privilegeService.getCurrentPrincipal();

            Long parentUserID = parentUser.getUserid();

            SysUser lastChildUser = sysUserService.findLastUserByParentID(parentUserID);
            String newChildBusinessno = null;
            if (lastChildUser != null) {
                newChildBusinessno = String.valueOf(Long.parseLong(lastChildUser.getBusinessno()) + 1);
            } else {
                newChildBusinessno = parentUser.getBusinessno() + "01";
            }

            newUser.setNtype(0);//表示娱乐城老板子账户
            newUser.setBusinessno(newChildBusinessno);
            newUser.setAdminid(parentUserID);
            newUser.setOuttime(TimeGreaterUilt.specifiedTime(Calendar.YEAR,
                    childUser.getTimeDifference() <= 0 ? 3
                            : childUser.getTimeDifference()));
            newUser.setPuserid(parentUserID);
            newUser.setMobile(childUser.getMobile());
            newUser.setPassword(QEncodeUtil.md5Encrypt(childUser.getPassword()));
            newUser.setRemark(childUser.getRemark());
            newUser.setProperty(childUser.getProperty());
            newUser.setState(childUser.getState());
            newUser.setCreatetime(new Date());
            // 新增子用户
            if (sysUserService.insertSelective(newUser) > 0) {
                //* 子用户分配角色
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setAdminid(parentUserID);
                sysUserRole.setUpdatetime(new Date());
                sysUserRole.setCreatetime(new Date());
                sysUserRole.setRoleid(childUser.getRole());
                sysUserRole.setUserid(newUser.getUserid());
                if (sysUserRoleService.insertSelective(sysUserRole) > 0)
                    return WebResult.success().toMap();
                else
                    return WebResult.failure("新增的子账户分配用户组失败").toMap();
            } else
                return WebResult.failure("增加子账户失败").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: getRoles
     * @Description: TODO(新增用户子角色)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "addusergroup", method = RequestMethod.POST)
    public Map<String, Object> addUserRole(String usergroupname, Long[] modules) {

        if (usergroupname == null || "".equals(usergroupname)) {
            return WebResult.failure("子角色名称不能为空").toMap();
        }

        Long userid = privilegeService.getCurrentPrincipal().getUserid();
        QuerySysRoleCondition condition = new QuerySysRoleCondition();
        condition.setAdminid(userid);
        condition.setNtype(4);
        SysRoleDto dto = sysRoleService.findByCondition(condition);
        if (dto != null) {

            SysRole role = new SysRole();
            role.setProleid(dto.getRoleid());
            role.setAdminid(userid);
            role.setNamecn(usergroupname);
            role.setSname("user define");
            role.setNtype(0); //用户自定义
            role.setUpdatetime(new Date());
            role.setState(1);
            role.setIsdefault(1);
            role.setIsshare(1);
            role.setRemark("自定义子角色");

            if (sysRoleService.insertSelective(role) > 0) {

                if (modules != null && modules.length > 0) {
                    List<SysRoleModule> sysRoleModules = new ArrayList<SysRoleModule>();
                    Date updatetime = new Date();
                    for (Long module : modules) {
                        SysRoleModule rm = new SysRoleModule();
                        rm.setRoleid(role.getRoleid());
                        rm.setModuleid(module);
                        rm.setAdminid(userid);
                        rm.setUpdatetime(updatetime);
                        sysRoleModules.add(rm);
                    }
                    sysRoleModuleService.setupRoleModule(sysRoleModules);
                }

                return WebResult.success().toMap();

            } else
                return WebResult.failure("新增子角色失败,请稍后重试").toMap();
        } else {
            return WebResult.failure("不在用户组中，请与管理员联系").toMap();
        }
    }

    /**
     * @Title: getRoles
     * @Description: TODO(获取角色权限)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "getUserGroupModule", method = RequestMethod.POST)
    public Map<String, Object> getRoleModules(final Long usergroupid) {
        try {

            return sysModuleService.getRoleModules(usergroupid);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }


    /**
     * @Title: getUserPlaces
     * @Description: TODO(获取用户下的所有场地)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "getuserplaces", method = RequestMethod.GET)
    public Map<String, Object> getUserPlaces() {
        try {
            QueryPubPlaceCondition condition = new QueryPubPlaceCondition();
            condition.setAdminId(privilegeService.getCurrentPrincipal().getUserid());
            List<PubPlaceDto> placeDtos = pubPlaceService.findListsByCondition(condition);
            List<PlaceVo> places = new ArrayList<PlaceVo>();
            for (PubPlaceDto pubPlace : placeDtos) {
                PlaceVo place = new PlaceVo();
                place.setPlaceid(pubPlace.getPlaceid());
                place.setPlacename(pubPlace.getAddress());
                places.add(place);
            }
            return WebResult.success().put("data", places).toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: getUserPlaces
     * @Description: TODO(获取用户下的所有场地)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "setuprolemodules", method = RequestMethod.POST)
    public Map<String, Object> setRoleModule(Long roleid, Long[] modules) {
        try {
            if (roleid == null || roleid.equals(0)) {
                return WebResult.failure("角色为空,非法操作").toMap();
            } else if (modules == null || modules.length <= 0) {
                return WebResult.failure("权限为空,非法操作").toMap();
            } else {
                /* 设置角色的权限之前，先清空掉原来已经设置好的权限 */
                Long adminid = privilegeService.getCurrentPrincipal().getUserid();
                SysRoleModuleCriteria criteria = new SysRoleModuleCriteria();
                criteria.or().andRoleidEqualTo(roleid).andAdminidEqualTo(adminid);
                sysRoleModuleService.deleteByCriteria(criteria);

                List<SysRoleModule> sysRoleModules = new ArrayList<SysRoleModule>();
                Date updatetime = new Date();
                for (Long module : modules) {
                    SysRoleModule rm = new SysRoleModule();
                    rm.setRoleid(roleid);
                    rm.setModuleid(module);
                    rm.setAdminid(adminid);
                    rm.setUpdatetime(updatetime);
                    sysRoleModules.add(rm);
                }

                if (sysRoleModuleService.setupRoleModule(sysRoleModules) > 0) {
                    return WebResult.success().toMap();
                } else {
                    return WebResult.failure("角色授权失败,请与管理员联系").toMap();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: getUserPlaces
     * @Description: TODO(获取用户下的所有场地)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "setuserplaces", method = RequestMethod.POST)
    public Map<String, Object> setUserPlaces(Long user, Long[] place) {
        try {
            if (user == null || user.equals(0)) {
                return WebResult.failure("非法操作").toMap();
            } else if (place == null || place.length <= 0) {
                return WebResult.failure("非法操作").toMap();
            } else {
                sysUserPlaceService.removeByUserID(user);//删除用户管理的场地
                Long adminid = privilegeService.getCurrentPrincipal().getUserid();
                List<SysUserPlace> userPlaces = new ArrayList<SysUserPlace>();
                for (Long id : place) {
                    SysUserPlace userPlace = new SysUserPlace();
                    userPlace.setPlaceid(id);
                    userPlace.setUserid(user);
                    userPlace.setAdminid(adminid);
                    userPlaces.add(userPlace);
                }
                if (sysUserPlaceService.addBatch(userPlaces) > 0) {
                    return WebResult.success().toMap();
                } else {
                    return WebResult.failure("分配场地失败,请与管理员联系").toMap();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: getUserPlaces
     * @Description: TODO(获取用户下的所有场地)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "clearuserplaces", method = RequestMethod.POST)
    public Map<String, Object> setUserPlaces(Long user) {
        try {
            if (user == null || user.equals(0)) {
                return WebResult.failure("非法操作").toMap();
            } else {
                sysUserPlaceService.removeByUserID(user);
                return WebResult.success().toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param passwordType 密码类型（1.登录密码 / 2.提现密码）
     * @param mobileCode   手机号码
     * @param oldpassword  旧密码
     * @param newpassword  新密码
     * @return
     * @Title: changePassword(int passwordType, String mobileCode, String oldpassword, String newpassword, HttpSession session)
     * @Description: TODO(修改密码)
     * @author Jerry Chan
     * @date 2016/12/20 11:26
     */
    private Map<String, Object> changePassword(int passwordType, String mobileCode, String oldpassword, String
            newpassword) throws Exception {

        if (mobileCode == null || "".equals(mobileCode)) {
            return WebResult.failure("短信验证码不能为空").toMap();
        }
        if (oldpassword == null || "".equals(oldpassword)) {
            return WebResult.failure("旧密码不能为空").toMap();
        }
        if (newpassword == null || "".equals(newpassword)) {
            return WebResult.failure("新密码不能为空").toMap();
        }

        if (oldpassword.equals(newpassword)) {
            return WebResult.failure("旧密码与新密码一致").toMap();
        }

        SysUser user = sysUserService.selectByPrimaryKey(privilegeService.getCurrentPrincipal().getUserid());
        //如果旧密码不等于原始登录密码或者旧密码不等于原始提现密码
        if (!QEncodeUtil.md5Encrypt(oldpassword).equals(user.getPassword()) && !QEncodeUtil.md5Encrypt(oldpassword).equals(user.getTransferpassword())) {
            return WebResult.failure("旧密码错误，请重新输入").toMap();
        } else if (QEncodeUtil.md5Encrypt(newpassword).equals(user.getTransferpassword()) || QEncodeUtil.md5Encrypt(newpassword).equals(user.getPassword())) {
            return WebResult.failure("提现密码不能与登录密码一致").toMap();
        }

        VaildPhone validPhone = PhoneCodeCacheTimer.get(mobileCode);
        if (validPhone == null) {
            return WebResult.failure("验证码错误,请重新输入").toMap();
        } else if (validPhone.getValidTime() < new Date().getTime()) {
            PhoneCodeCacheTimer.remove(mobileCode);
            return WebResult.failure("短信验证码已过期，请重新获取").toMap();
        }else{
            if (user == null || "".equals(user.getMobile())) {
                return WebResult.failure("用户没有手机号码").toMap();
            }else if (!validPhone.getPhone().equals(user.getMobile())) {
                return WebResult.failure("与获取短信的手机号码一致").toMap();
            } else {
                PhoneCodeCacheTimer.remove(mobileCode);
            }
        }

        SysUser newUser = new SysUser();
        newUser.setUserid(user.getUserid());
        newUser.setAdminid(user.getUserid());
        newUser.setUpdatetime(new Date());
        if (passwordType == 1) {
            newUser.setPassword(QEncodeUtil.md5Encrypt(newpassword));
        } else if (passwordType == 2) {
            newUser.setTransferpassword(QEncodeUtil.md5Encrypt(newpassword));
        }

        if(sysUserService.updateByPrimaryKeySelective(newUser) > 0){
            return WebResult.success().toMap();
        }else{
            return WebResult.failure("更改密码失败，请与管理员联系").toMap();
        }
    }


}
